/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.git

import com.google.inject.Inject
import com.jcraft.jsch.Session
import javax.inject.Named
import javax.inject.Provider
import org.eclipse.jgit.api.TransportConfigCallback
import org.eclipse.jgit.transport.JschConfigSessionFactory
import org.eclipse.jgit.transport.OpenSshConfig
import org.eclipse.jgit.transport.SshSessionFactory
import org.eclipse.jgit.transport.SshTransport
import org.eclipse.jgit.transport.Transport
import org.eclipse.jgit.util.FS
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
class SshProvider implements Provider<TransportConfigCallback> {
	val static LOG = LoggerFactory.getLogger(SshProvider)

	String sshkeyPath;

	@Inject(optional=true)
	@Named("taomu.git.ssh.keypath")
	new(String sshKeyPath) {
		this.sshkeyPath = sshKeyPath
	}

	override get() {
		LOG.info("Guice从SshProvider中获取TransportConfigCallback实例");
		return new TransportConfigCallback() {
			override configure(Transport transport) {
				var sshTransport = transport as SshTransport;
				var jcsf = new JschConfigSessionFactory() {
					override configure(OpenSshConfig.Host host, Session session) {
						session.setConfig("StrictHostKeyChecking", "no");
					}

					override createDefaultJSch(FS fs) {
						var jSch = super.createDefaultJSch(fs);
						LOG.info("JschConfigSessionFactory设置sshkeypath:{}", sshkeyPath);
						jSch.addIdentity(sshkeyPath);
						return jSch;
					}
				};
				SshSessionFactory.instance = new JschConfigSessionFactory() {
					override configure(OpenSshConfig.Host host, Session session) {
						session.setConfig("StrictHostKeyChecking", "no");
					}

					override createDefaultJSch(FS fs) {
						var jSch = super.createDefaultJSch(fs);
						LOG.info("JschConfigSessionFactory设置sshkeypath:{}", sshkeyPath);
						jSch.addIdentity(sshkeyPath);
						return jSch;
					}
				};
				sshTransport.setSshSessionFactory(jcsf);
			}
		}
	}

}
